package arduino
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.Endian;
	
	public class ArduinoConnection
	{				
		private static const EOL_DELIMITER: String = "\n";
		private var _socket: Socket;
		private var _proxyAddress: String = "127.0.0.1";
		private var _proxyPort: uint = 5333;
		
		public function ArduinoConnection()
		{
		}
		
		//getConnection
		public function getArduinoConnection() : void
		{
			_socket = new Socket();
			_socket.addEventListener( Event.CONNECT, onConnect );			
			_socket.addEventListener( Event.CLOSE, onClose );			
			_socket.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData );
			_socket.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
			_socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onSecurityError );
			_socket.endian = Endian.LITTLE_ENDIAN;
			_socket.connect(_proxyAddress, _proxyPort);
		}
		
		private function onConnect(event:Event):void
		{
		}
		
		private var buffer:String = "";
		
		private function onSocketData(event : ProgressEvent):void
		{
			var data:String = _socket.readUTFBytes( _socket.bytesAvailable );
			buffer += data;

			var msg:String;
			var index:int;
			while((index = buffer.indexOf(EOL_DELIMITER)) > -1)
			{
				msg = buffer.substring(0, index);
				buffer = buffer.substring(index + 1);
			}				

		}
		private function onClose(event:Event):void
		{
			trace("Socket Closed");
		}
		private function onIOError(event: IOErrorEvent):void
		{
			trace("IOErrorEvent : " + event.text);
		}
		private function onSecurityError(event: SecurityErrorEvent):void
		{
			trace("SecurityErrorEvent : " + event.text);
		}
		
		//public functions (Name = TOGGLE_LED_STATE);
		public function sendData(functionName : String):void
		{
			if(!_socket.connected)
			{
				trace("You must be connected to send a command to the Arduino.");
				return;
			}
			
			_socket.writeUTFBytes(functionName);
			_socket.flush();
		}
	}
}